<template>
  <div class="dialog">
    <el-dialog :title="editId ? '编辑角色' : '添加角色'" :visible.sync="visible" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="form.code"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('form')"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
   </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue'
import { saveOrUpdate, getRole } from '@/services/role'

export default Vue.extend({
  name: 'RoleDialog',
  data () {
    return {
      form: {
        id: null,
        name: '',
        code: '',
        description: ''
      },
      rules: {}
    }
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    editId: {
      type: Number || null,
      default: null
    },
    closeDialog: { type: Function }
  },
  methods: {
    async onSubmit () {
      try {
        // 1. 表单验证
        await (this.$refs.form).validate()
        // 2. 验证通过 -> 提交表单
        const { data } = await saveOrUpdate(this.form)
        console.log(data)
        // 3. 处理请求结果
        if (data.code === '000000') {
          this.closeDialog()
          this.$message.success('提交成功')
        }
      } catch (err) {
        console.log('error submit!!')
        return false
      }
    },
    closeModal () {
      console.log('close')
    },
    async loadInfo () {
      const { data } = await getRole(this.editId || null)
      if (data.data.menuInfo) {
        this.form = data.data.menuInfo
      }
      if (data.code === '000000') {
        const res = data.data
        this.form = {
          id: res.id,
          name: res.name,
          code: res.code,
          description: res.description
        }
      }
    }
  },
  created () {
    if (this.editId) {
      this.loadInfo()
    }
  }
})
</script>

<style lang="scss" scoped>

</style>
